/**********************************************************************
 Name:  CreateAuditControl
 Purpose:Create Audit Plan                                      
======================================================
History                                                            
-------                                                            
VERSION  AUTHOR            DATE              DETAIL                                
   1.0         li siheng         2010-03-15        Create          
***********************************************************************/

public class CreateAuditControl{
    
    public map<id,audit__c> AuditMap{get;set;}
    public List<SelectOption> OptionList{get;set;}
    public String[] SortValue{get;set;}
    public list<in_store_visit__c> isvl{get;set;}
    public List<SelectOption> RegionList{get;set;}
    public list<SelectOption> TSRList{get;set;}
    public String RegionValue{get;set;}
    public String SubRegionValue{get;set;}
    public String AreaValue{get;set;}
    public String CityValue{get;set;}
    public string TSRL{get;set;}
    public user CurrentUser;
    public list<place__c> PlaceL{get;set;}
    public list<User> AllUserList{get;set;}
    public List<user> AllTsr{get;set;}
    public boolean SearchDateB=true;
    
    list<audit__c> insertL=new list<audit__c>();
    
    public list<ISVEntry> IsvE{get;set;} 
    public list<ISVEntry> currentISV{get;set;} 
    map<string,ISVEntry> haveIsvE = new map<string,ISVEntry>();
    public string msg{get;set;}
    public string msgInfo{get;set;}
    
    public Audit__c SearchDate{
        get{
            if(SearchDateB){
                searchdate=new audit__c();
                searchdate.searchdate__c=null;
                SearchDateB=false;
            }
            return searchdate;
        }
         set;
    }
     public boolean AuditB=true;
     public boolean NewAuditPlan;
     Public Audit_Plan__c AuditPlanTemp;
     public Audit__c Audit{
        get{
            if(AuditB){
                Audit=new audit__c();
                audit.plan_date__c=null;
                AuditB=false;
            }
            return audit;
        }
        set;}
        
    //========构造函数  START
    public CreateAuditControl() {
    
        NewAuditPlan = false;
        if(OptionList==null)
            OptionList= new List<SelectOption>();
        SortValue=new String[]{};     
            
        //找出所有place
        placeL=[select Id,Name,Region__r.Name,Subregion__r.Name,Area__r.Name,PlaceType__c  from Place__c];
        //=====根据user确定下拉列表值=======
        if(TSRList==null)
                TSRList=new List<SelectOption>();
        else
                TSRList.clear();
        
        alltsr=new list<user>();       
        CurrentUser=[select Id,Name,UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        
        Profile prof=[select Name from Profile where Id=: UserInfo.getProfileId()];
        
        //如果是系统管理员加载所有的TSR否则加载所有的
       AllUserList=[select id,managerID,FunctionDepartment__c,Title__c,name,UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c
                              from User where FunctionDepartment__c !='Medical Sales' order by Name];//搜出所有用户，排除MSR
       
       if(prof.Name=='System Administrator' || prof.Name=='系统管理员')
        {
            for(User u:AllUserList)//添加所有TSR
            {
                if(u.Title__c == 'Sales Rep' && u.FunctionDepartment__c =='Trade Sales'){
                    Alltsr.add(u);
                    TSRList.add(new SelectOption(u.Id,u.Name));
                }
            }
        }else{
            set<id> US=new set<id>();
            Us.add((id)userinfo.getuserid());
            SearchTsr(us);
        }
        
        RegionList=new List<SelectOption>();
        RegionList.add(new SelectOption('0','所有大区'));
        if(CurrentUser.UserRegion__c == NULL)
        {
            for(Place__c p:PlaceL){
                if(p.PlaceType__c=='Region'){
                    RegionList.add(new SelectOption(p.Name,p.Name));
                }
                
            }
                
        }
        else
        {
            RegionList.add(new SelectOption(CurrentUser.UserRegion__c,CurrentUser.UserRegion__c));
        }
        
        //=======根据user确定下拉列表值  END=====
        
        //选取列表初始化；
        if(isve==null)
            isve=new List<ISVEntry>();
        else
            isve.clear();
        if(currentISV == null)
            currentISV =new List<ISVEntry>();
        else
            currentISV.clear();                
                
        
        
    } 
    //=======构造函数  END
    
    //========区域下拉列表值设置   start====
    public List<SelectOption> SubRegionList
    {
        get
        {
            if(SubRegionList==null){
                SubRegionList=new List<SelectOption>();
            }else{
                SubRegionList.clear();
            }
            
            SubRegionList.add( new SelectOption('0','所有片区'));
            if(CurrentUser.UserSubRegion__c == NULL)
            {
                for(Place__c p:PlaceL)
                {
                    if( p.PlaceType__c=='Sub-region' && p.Region__r.Name==RegionValue ){//
                    //   system.assert(false,'====:'+regionvalue);
                       SubRegionList.add(new SelectOption(p.Name,P.Name)); 
                    }
                    
                }
            }
            else
            {
                SubRegionList.add(new SelectOption(CurrentUser.UserSubRegion__c,CurrentUser.UserSubRegion__c));
            }
            return SubRegionList;
        }
        set;    
    }
    
    public List<SelectOption> AreaList
    {
        get
        {
            if(AreaList==null)
                AreaList=new List<SelectOption>();
            else
                AreaList.clear();
            
            AreaList.add(new SelectOption('0','所有区域'));
            if(CurrentUser.UserAreaValue__c==NULL)
            {
                for(Place__c p:PlaceL)
                {
                    if(p.PlaceType__c=='Area' && p.Subregion__r.Name==SubRegionValue){//
                        AreaList.add(new SelectOption(p.Name,P.Name));
                    }
                    
                }
            }
            else
            {
                List<String> arr=String.valueOf(CurrentUser.UserAreaValue__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        AreaList.add(new SelectOption(s,s));
                }
            }
            return  AreaList;
        }
        set;
    }
    
     public List<SelectOption> CityList
    {
        get
        {
            if(CityList==null)
                CityList=new List<SelectOption>();
            
            CityList.clear();
            CityList.add(new SelectOption('0','所有城市'));
            if(CurrentUser.UserCity__c==NULL)
            {
                if( AreaValue != NULL)
                {
                    for(Place__c p:PlaceL)
                    {
                        if(p.PlaceType__c=='City' && p.Area__r.Name==AreaValue){
                            CityList.add(new SelectOption(P.Name,P.Name));
                        } 
                    }   
                }
            }
            else
            {
                List<String> arr=String.valueOf(CurrentUser.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        CityList.add(new SelectOption(s,s));
                }
            }
            return CityList;
        }
       set;
    }
    //=============区域下拉列表值设置  END=============
    
    
    //====递归找出下级的所有TSR ====
    
    public void SearchTsr(set<id> US){
        set<id> tempS=new set<id>();
         temps.clear();
        for(user u:AllUserList){
            if(us.contains(u.managerID)){
                if(u.Title__c == 'Sales Rep' && u.FunctionDepartment__c=='Trade Sales'){
                    alltsr.add(u);
                    TSRList.add(new SelectOption(u.Id,u.Name));
                }else{
                    temps.add(u.id);
                }
            }
        }
        if(temps.size()>0){
            SearchTsr(temps);
        }
    }
    
    //====筛选要显示的TSR
    public void TSRFilter(){
        TSRlist.clear();
        for(user u:alltsr){
            if((u.UserCity__c==CityValue || cityvalue=='0' ) && ( u.UserAreaValue__c==AreaValue || areavalue=='0') &&  (u.UserSubRegion__c==subregionvalue || subregionvalue=='0') &&  (u.UserRegion__c==regionvalue || regionvalue=='0')){
                TSRList.add(new SelectOption(u.Id,u.Name));
            }
        }
    }
    
    public void SaveRecord(){
        msgInfo = null;
        Boolean haveChecked = false;
        for(integer i=0;i<currentISV.size();i++){
            if(currentISV[i].checked)
            {
                haveChecked = true;
                if(!haveIsvE.containsKey(currentISV[i].ISVLs.id))
                {
                    isve.add(currentISV[i]);
                    haveIsvE.put(currentISV[i].ISVLs.id,currentISV[i]);
                }
                    
            }
        }    
        if(haveChecked == false)
        {
            msgInfo = '请选择店内拜访信息';
        }   
    }
    
    
    
    public void search(){
        list<id> idList=new list<id>();//储存已存在ISV ID；

        for(integer i=0;i<isve.size();i++){
            if(isve[i].checked){
                idlist.add(isve[i].ISVLs.id);
            }
        }
        
        if(searchDate.searchdate__c!=null){
            isvl=[select id,OutletName_del__c, name, Outlet_Code__c,  CreatedBy.Alias  , visit_date__c,OutletName_del__r.name from in_store_visit__c where visit_date__c =:searchDate.searchdate__c and ownerid__c =:TSRL.substring(0,15) and id not in:idlist and (( InventoryDisplayPriceGreaterThan0__c >0 or CompetitorDistributionTotal__c >0) or ( HaveSurvey__c =: true)) order by visit_date__c limit 10000]; 
        }
        else{
            isvl=[select id,OutletName_del__c,name,visit_date__c,Outlet_Code__c,  CreatedBy.Alias  ,OutletName_del__r.name from in_store_visit__c where ownerid__c =:TSRL.substring(0,15) and id not in:idlist and  (( InventoryDisplayPriceGreaterThan0__c >0 or CompetitorDistributionTotal__c >0)or ( HaveSurvey__c =: true) )  order by visit_date__c limit 10000]; 
        }

        currentISV.clear();
        for(in_store_visit__c i:isvl){
            currentISV.add(new ISVEntry(i));
        }        
    }
    
    
    
    public PageReference Submit(){
        if(Audit.Plan_Date__c==null){
            msg='请填写拜访日期。';
            return null;
        }
//modify the date rule
/*        
        if(Audit.Plan_Date__c<=date.today()){
            msg='不能创建或修改当天以及当天以前的拜访计划。';
            return null;
        }
*/        
        
        if(isve.size()>0){
            //搜出对应Audit Plan，无则创建;
            list<Audit_Plan__c> apl=[select id,name,audit_date__c from audit_plan__c where audit_date__c =: audit.plan_date__c and ownerid =:userinfo.getuserid() limit 1];
            audit_plan__c ap=new Audit_plan__c();
            if(apl.size()>0){
                ap=apl[0];
            }else{
                ap=new audit_plan__c(audit_date__c=audit.plan_date__c);
                insert ap;
                NewAuditPlan = true;
                AuditPlanTemp = ap;
            }
            date planDate;
            Map<string,audit__c> insertM = new Map<string,audit__c>();
            for(ISVEntry isv:isve){
                if(isv.checked){
                    plandate=audit.plan_date__c;
                    audit__c audit=new audit__c(name=isv.isvls.OutletName_del__r.name,Audit_Plan__c=ap.id,sort__c=0,In_Store_Visit__c=isv.ISVLs.id,Plan_Date__c=plandate,owner__c=userinfo.getuserid(),UniqueId__c=string.valueof(plandate.year())+string.valueof(plandate.month())+string.valueof(plandate.day())+userinfo.getUserId().substring(0,15)+string.valueof(isv.isvls.id).substring(0,15));
                    insertl.add(audit);
                    insertM.put(audit.In_Store_Visit__c,audit);
                }
            }
            List<Audit__c> ExitAuditList=[select id,name,Outlet__c,UniqueId__c,In_Store_Visit__c  from Audit__c where Plan_Date__c =:audit.plan_date__c and Owner__c=: userinfo.getuserid() order by sort__c];
            if(ExitAuditList.size() > 0){
                for(Audit__c aud : ExitAuditList)
                {
                    if(!insertM.containsKey(aud.In_Store_Visit__c))
                    {
                        insertl.add(aud);
                    }
                }
            }
            auditmap = new map<id,audit__c>();

        for(Audit__c aud:insertl){
            if(aud != null)
            {
                if(aud.In_Store_Visit__c != null)
                    auditmap.put(aud.In_Store_Visit__c,aud);
            }
                
        } 
         for(Audit__c a:insertl){
            OptionList.add(new SelectOption(a.In_Store_Visit__c, a.name+''));
         }         

        }
   
        return Page.SortAuditPage;
    }

    public PageReference save(){
        list<audit__c> updateAuditList=new list<audit__c>();
        //按照sortvalue排序
        
        for(integer i=0;i<SortValue.size();i++){
            Audit__c audit=new Audit__c();
            audit=auditmap.get(SortValue[i]);
            audit.sort__c=i+1;
            updateAuditList.add(audit);
        }
        upsert updateAuditList UniqueId__c;
       // update updateauditlist;
        pageReference pr = new pageReference('/apex/AuditPlanPage'); 
        pr.setredirect(true);
        return pr;
    }

    
    public pageReference cancel(){

        if(NewAuditPlan && (AuditPlanTemp != null))
            delete AuditPlanTemp;
    
        pageReference pr = new pageReference('/apex/auditplanpage');           
        pr.setredirect(true);      
        return pr;
    }
    
    private final ApexPages.StandardController controller;
    
    
    static testMethod  void test()
    {
        Profile p = [select id from profile where Name='Regional General Manager' limit 1];
        User u2 = new User(alias = 'standtss', email='sdardr@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',Title__c='TSR',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',IsActive=true,
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',
        timezonesidkey='America/Los_Angeles', username='stsers@testorg.com');
        insert u2;  
        user u=[select id from user where Title__c = 'Sales Rep' and FunctionDepartment__c='Trade Sales' and isactive=true limit 1];
        Routing_Plan_And_Visit__c RPAV=new Routing_Plan_And_Visit__c(Visit_Date__c=date.today());
        insert rpav;
        in_store_visit__c isv=new in_store_visit__c();
        isv.LabelIsInTheCorrectPlace__c=true;
        isv.MainShelfDisplayIsStandard__c=true;
        isv.Main_Shelf_Facing__c=23;
        isv.End_Time__c=datetime.now();
        isv.Start_Time__c=datetime.now();
        isv.RoutingPlanAndVisit__c=rpav.id;
        isv.OutletName_del__c=[select id from account limit 1].id;
        insert isv;
        system.runas(u2){
            
            CreateAuditControl Audit=new CreateAuditControl();
            audit.SearchDate.searchdate__c=date.today();
            audit.TSRL=u.id;
            audit.search();
            for(ISVEntry isvent:audit.IsvE){
                isvent.checked=true;
            }
            audit.submit();
            audit.cancel();
        }
    }
    
}